package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"srv/model/es"

	"srv/internal/svc"
	"srv/sesame"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchGoodsLogic {
	return &SearchGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SearchGoodsLogic) SearchGoods(in *sesame.SearchGoodsRequest) (*sesame.SearchGoodsResponse, error) {
	var buf bytes.Buffer
	query := map[string]interface{}{}
	if in.Keyword != "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"GoodsTitle": in.Keyword,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_all": map[string]interface{}{},
			},
		}

		if err := json.NewEncoder(&buf).Encode(query); err != nil {
			log.Fatalf("Error encoding query: %s", err)
		}

		// Perform the search request.
		res, err := es.Es.Search(
			es.Es.Search.WithContext(context.Background()),
			es.Es.Search.WithIndex("goods"),
			es.Es.Search.WithBody(&buf),
			es.Es.Search.WithTrackTotalHits(true),
			es.Es.Search.WithPretty(),
		)
		if err != nil {
			log.Fatalf("Error getting response: %s", err)
		}
		defer res.Body.Close()
		fmt.Println(res)
		r := map[string]interface{}{}
		json.NewDecoder(res.Body).Decode(&r)
		var list []sesame.GoodsItem
		for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
			source := hit.(map[string]interface{})["_source"].(map[string]interface{})

			list = append(list, sesame.GoodsItem{
				GoodsId:    int64(source["GoodsId"].(float64)),
				GoodsTitle: source["GoodsTitle"].(string),
				GoodsCover: source["GoodsCover"].(string),
				GoodsPrice: float32(source["GoodsPrice"].(float64)),
			})
			fmt.Println(source)
		}
	}
	return &sesame.SearchGoodsResponse{}, nil
}
